# Maintainer: Kyle Keen <keenerd@gmail.com>
# Contributor: Mihai Militaru <mihai militaru at xmpp dot ro>
# Contributor: carstene1ns <arch carsten-teibes.de>

pkgname=mbedtls
pkgver=2.28.2
pkgrel=1
pkgdesc="Portable cryptographic and SSL/TLS library, aka polarssl"
arch=('loong64' 'x86_64')
url="https://tls.mbed.org"
license=('Apache')
depends=('glibc' 'sh')
checkdepends=('python')
makedepends=('cmake' 'python')
provides=('polarssl' 'libmbedcrypto.so' 'libmbedtls.so' 'libmbedx509.so')
replaces=('polarssl')
conflicts=('polarssl')
options=('staticlibs')
source=(https://github.com/ARMmbed/mbedtls/archive/${pkgname}-${pkgver}.tar.gz)
sha256sums=('1db6d4196178fa9f8264bef5940611cd9febcd5d54ec05f52f1e8400f792b5a4')
b2sums=('b1b663002c45a23e853273b58ea41dcd61f9a55b586d8cf73bdcbde574692dce1002e3ef4a4b686b145c47d94363e665e9baf477032de3c8efec3289dd997e7a')

prepare() {
  cd "$pkgname-$pkgname-$pkgver"
  # enable flags for non-embedded systems
  sed -i 's|//\(#define MBEDTLS_THREADING_C\)|\1|' include/mbedtls/config.h
  sed -i 's|//\(#define MBEDTLS_THREADING_PTHREAD\)|\1|' include/mbedtls/config.h
}

build() {
  cd "$pkgname-$pkgname-$pkgver"
  cmake \
    -B build \
    -DCMAKE_INSTALL_PREFIX=/usr \
    -DCMAKE_C_FLAGS="${CFLAGS} -ffat-lto-objects" \
    -DMBEDTLS_FATAL_WARNINGS=OFF \
    -DCMAKE_VERBOSE_MAKEFILE=ON \
    -DUSE_SHARED_MBEDTLS_LIBRARY=ON \
    -DCMAKE_INSTALL_RPATH=
  make -C build
}

check() {
  cd "$pkgname-$pkgname-$pkgver"
  make -C build test
}

package() {
  cd "$pkgname-$pkgname-$pkgver"
  make -C build DESTDIR="$pkgdir" install

  # rename generic utils
  local _prog _baseprog
  for _prog in "$pkgdir"/usr/bin/*; do
	_baseprog=$(basename "$_prog")
    mv -v "$_prog" "${_prog//$_baseprog/mbedtls_$_baseprog}"
  done

  # fixup static lib permissions
  chmod 644 "$pkgdir"/usr/lib/*.a
}
